//
//  NetworkOperation.m
//  iMAL
//
//  Created by Stefano Pigozzi on 2/1/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "NetworkOperation.h"


@implementation NetworkOperation

@synthesize url;
@synthesize context;
@synthesize mal;

-(NetworkOperation *) initWithUrl:(NSString *) initurl managedObjectContex:(NSManagedObjectContext *) initcontext malHandler: (MALHandler *) initmal
{
	self = [super init];
	if (self != nil) {
		self.url = initurl;
		self.context = initcontext;
		self.mal = initmal;
	}
	return self;
}

-(void)main {
    if ( self.isCancelled ) return;
    if ( nil == self.url ) return;
    NSData *fetchedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.url]]; 
    if ( self.isCancelled ) return;
	// image
	if([self.url isMatchedByRegex:@"http://cdn.myanimelist.net/images/anime/[0-9]+/[0-9]+.jpg"]){
		[self.context fetchAnimeWithImage:self.url];
		NSManagedObject * o = [self.context fetchAnimeWithImage:self.url];
		
		NSString * filename = [NSString stringWithFormat:@"/Users/%@/Library/Application Support/iMAL/images/%@.jpg",NSUserName(),[o valueForKey:@"anime_id"]];
		
		[fetchedData writeToFile:filename atomically:NO];
		[o setValue:filename forKey:@"image_path"];
		
		NSNumber * newCurrent = [NSNumber numberWithInt:[[self.mal valueForKey:@"progressCurrent"] intValue]+1];
		[self.mal setValue:newCurrent forKey:@"progressCurrent"];
		[self.mal setValue:[NSString stringWithFormat:@"Downloading icon for: %@", [o valueForKey:@"title"]] forKey:@"progressMessage"];
		if([[self.mal progressCurrent] intValue] >= [[self.mal progressMaximum] intValue]){
			[self.mal hideProgressSheet];
		}
		return;
	}
	// deep anime
	if([self.url isMatchedByRegex:@"/anime/[0-9]+"]){
		int anime_id = [[self.url stringByMatching:@"/anime/([0-9]+)" withReferenceFormat:@"$1"] intValue];
		NSManagedObject * o = [self.context fetchOrCreateAnimeWithId:anime_id];
		
		NSString * response_html = [[NSString alloc] initWithData:fetchedData encoding:NSUTF8StringEncoding];
		if(response_html == nil){ // backing off to ASCII encoding if UTF8 went wrong
			response_html = [[NSString alloc] initWithData:fetchedData encoding:NSASCIIStringEncoding];
		}
		NSString * title_alternatives = [response_html stringByMatching:@"Synonyms: ([^\"]+)\"" withReferenceFormat:@"$1"];
		[o setValue:title_alternatives forKey:@"title_alternatives"];
		
		NSString * image = [response_html stringByMatching:@"(http://cdn.myanimelist.net/images/anime/[0-9]+/[0-9]+.jpg)" withReferenceFormat:@"$1"];
		
		if([o valueForKey:@"image"]==nil){
			[o setValue:image forKey:@"image"];
			[[self.mal scheduledOperations] addOperation:[[NetworkOperation alloc] initWithUrl:image managedObjectContex:self.context malHandler:self.mal]];
		} else {
			NSNumber * newCurrent = [NSNumber numberWithInt:[[self.mal valueForKey:@"progressCurrent"] intValue]+1];
			[self.mal setValue:newCurrent forKey:@"progressCurrent"];
			[self.mal setValue:[NSString stringWithFormat:@"Skipping icon for: %@", [o valueForKey:@"title"]] forKey:@"progressMessage"];
		}
		
		NSNumber * newCurrent = [NSNumber numberWithInt:[[self.mal valueForKey:@"progressCurrent"] intValue]+1];
		[self.mal setValue:newCurrent forKey:@"progressCurrent"];
		[self.mal setValue:[NSString stringWithFormat:@"Importing: %@", [o valueForKey:@"title"]] forKey:@"progressMessage"];
		if([[self.mal progressCurrent] intValue] >= [[self.mal progressMaximum] intValue]){
			[self.mal hideProgressSheet];
		}
		[response_html release];
		return;
	}
	
}



@end
